package org.canaan.http.urlpair.core;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Map;

/**
 * url key=value参数,创建者
 *
 * @author Canaan
 * @date 2017/6/29 0029
 */
class UrlPairBuilder {


    /**
     * map转 key=value字符串
     *
     * @param map
     * @return
     */
    private String mapToString(Map<String, ?> map) {
        if (map.size() == 0) {
            return "";
        }

        ParseChain parseChain = new ParseChain();
        StringBuilder sb = new StringBuilder();

        //验证map 的key 是不是一个String类型
        try {
            for (String key : map.keySet()) {
                break;
            }
        } catch (Exception e) {
            return "";
        }

        for (String key : map.keySet()) {
            Object value = map.get(key);
            String pair = parseChain.doParse(key, value);
            if (pair == null || pair.trim().equals("")) {
                continue;
            }
            sb.append(pair).append("&");
        }

        if (sb.length() != 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }

    ;

    /**
     * 自定义对象转 key=value字符串
     *
     * @param o
     * @return
     */
    private String objectToString(Object o) {
        Class<? > clazz = o.getClass();
        Field[] fields = clazz.getDeclaredFields();

        StringBuilder sb = new StringBuilder();
        ParseChain parseChain = new ParseChain();
        //取得各字段
        for (Field field : fields) {
            field.setAccessible(true);
            Object value;
            try {
                value = field.get(o);
            } catch (IllegalAccessException e) {
                continue;
            }
            String key = field.getName();
            String pair = parseChain.doParse(key, value);
            if (pair == null || pair.trim().equals("")) {
                continue;
            }
            sb.append(pair).append("&");
        }
        if (sb.length() != 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }


    /**
     * 将对象解析成key=value字符串
     *
     * @param o
     * @return
     */
    public String toURLPairString(Object o) {
        if (o == null) {
            return "";
        } else if (Utils.isBaseType(o)) {                //基本类型
            return o.toString();
        } else if (Map.class.isInstance(o)) {            //map类型
            Map<String, ?> map = (Map<String, ?>) o;
            return mapToString(map);
        } else if (Collection.class.isInstance(o)) {     //集合类型
            throw new IllegalStateException("无法解析一个集合");
        } else if (o.getClass().isArray()) {            //数组类型
            throw new IllegalStateException("无法解析一个数组");
        } else {                                        //对象自定义类型
            return objectToString(o);
        }
    }
}
